<template>

  <div class="header">
    <img id="return" src="https://sweetchenda.oss-cn-beijing.aliyuncs.com/20250728192143389.png" alt=""></img>
    <div class="search">
      <input type="text" placeholder="输入搜索..."></input>
      <span class="iconfont icon-sousuo"></span>
    </div>
    <ul class="text">
      <li>关于</li>
      <li>工具</li>
      <li>帮助</li>
    </ul>
    <ul class="picture">
      <li><span class="iconfont icon-xiaoxi"></span>
        <div class="circle">12</div>
      </li>
      <el-dialog class="sendMessage" v-model="dialogFormVisible" title="发送消息" width="500">
        <!-- <el-form :model="message">
          <el-form-item label="标题" :label-width="formLabelWidth">
            <el-input v-model="message.title" autocomplete="off" />
          </el-form-item>
          <el-form-item label="内容" :label-width="formLabelWidth">
            <el-input v-model="message.content" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmMessage">
              发送
            </el-button>
          </div>
        </template> -->
        <div class="notice">
          <div class="title">
            <span>|</span>消息公告
          </div>
          <div class="content">
            <div v-for="(item, index) in noticeList" :key="index" class="a">
              <el-button type="text" style="margin-left: 16px;color:#7F7F7F" @click="handleClick(index)">
                {{ item.title }}
              </el-button>
              <el-drawer v-model="item.drawer" title="I am the title" :with-header="false" id="notice-drawer">
                <span>{{ item.title }}</span>
                <br>
                <span>{{ item.content }}</span>
                <br>
                <el-button type="primary" plain id="queren" @click="btnyes(item.id)">确定</el-button>
                <br>
                <span>发布人：{{ item.manager }}</span>
                <br>
                <span>发布时间：{{ item.createTime }}</span>
              </el-drawer>
              <span>{{ item.createTime }}</span>
            </div>
          </div>
        </div>
      </el-dialog>
      <li><span class="iconfont icon-duanxin"></span>
        <div class="circle">7</div>
      </li>
      <li><span class="iconfont icon-lianxiren"></span>
        <div class="circle">5</div>
      </li>
    </ul>
    <!-- 这是下拉框 -->
    <el-dropdown placement="bottom">
      <div class="title">
        <p>Hello,{{ username }}</p>
        <img :src="avatar" alt="">
      </div>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item @click="formVisible = true">修改密码</el-dropdown-item>
        </el-dropdown-menu>
        <el-dropdown-menu>
          <el-dropdown-item @click="back">退出登录</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>

    <el-dialog v-model="formVisible" title="修改密码" width="500">
      <el-form :model="form">
        <el-form-item label="原密码" :label-width="labelWidth">
          <el-input v-model="form.oldPassword" type="password" autocomplete="off" show-password clearable />
        </el-form-item>
        <el-form-item label="新密码" :label-width="labelWidth">
          <el-input v-model="form.newPassword" type="password" autocomplete="off" show-password clearable />
        </el-form-item>
        <el-form-item label="确认新密码" :label-width="labelWidth">
          <el-input v-model="form.confirmPassword" type="password" autocomplete="off" show-password clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="formVisible = false">取消</el-button>
          <el-button :plain="true" type="primary" @click="handleSubmit">修改</el-button>
        </div>
      </template>
    </el-dialog>
    <!--下拉框  -->
  </div>
</template>

<script setup lang="ts" name="AppHeader">
import { useRouter } from 'vue-router'
import { ref, onMounted, reactive } from 'vue'
import request from '@/utils/http'
import { ElMessage } from 'element-plus'
import { JSEncrypt } from 'jsencrypt'
import { el } from 'element-plus/es/locales.mjs'

// RSA公钥
const RSA_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAM51dgYtMyF+tTQt80sfFOpSV27a7t9u
aUVeFrdGiVxscuizE7H8SMntYqfn9lp8a5GH5P1/GGehVjUD2gF/4kcCAwEAAQ==
-----END PUBLIC KEY-----`

// RSA加密函数
function encryptPassword(password: string): string {
  try {
    const encrypt = new JSEncrypt()
    encrypt.setPublicKey(RSA_PUBLIC_KEY)
    const encrypted = encrypt.encrypt(password)
    if (encrypted) {
      return encrypted
    } else {
      console.error('RSA加密失败')
      return password
    }
  } catch (error) {
    console.error('密码加密失败:', error)
    return password
  }
}
const username = ref('')
const avatar = ref('')
const formVisible = ref(false)
const labelWidth = ref('120px')
const form = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})



const dialogFormVisible = ref(false)
interface UserRoleResponse {
  code: string
  data: {
    roles: string[]
    nickname: string
  }
}
const nickname = ref<string>('')
const res = await request.get('/auth/user/info') as UserRoleResponse;
console.log(res);
nickname.value = res.data.nickname;

interface NoticeItem {
  title: string;
  content: string;
  createTime: string;
  drawer: boolean;
  id: number;
  manager?: string;
}
const noticeList = ref<NoticeItem[]>([])
const getNotice = async () => {
  try {
    const res = await request({
      url: '/jnotice/lish',
      params: {
        size: 999
      }
    })
    console.log(res)
    noticeList.value = res.data.list.map((item: any) => ({
      ...item,
      drawer: false,
    }))
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}
const handleClick = (index: number) => {
  noticeList.value[index].drawer = !noticeList.value[index].drawer;
}
onMounted(() => getNotice())

const btnyes = async (noticeId: number) => {
  try {
    const res = await request.post('/jnotice/lish/setNoticeName', {
      noticeId: Number(noticeId),
      username: nickname.value
    })
    console.log(res)
    // 关闭当前抽屉
    const currentNoticeIndex = noticeList.value.findIndex(item => item.id === noticeId)
    if (currentNoticeIndex !== -1) {
      noticeList.value[currentNoticeIndex].drawer = false
    }
  } catch (error) {
    console.error('设置通知名称失败:', error)
  }
}


async function handleSubmit() {
  // 表单验证
  if (!form.oldPassword) {
    ElMessage.warning('请输入原密码')
    return
  }
  if (!form.newPassword) {
    ElMessage.warning('请输入新密码')
    return
  }
  if (form.newPassword.length < 6) {
    ElMessage.warning('新密码长度不能少于6位')
    return
  }
  if (form.newPassword !== form.confirmPassword) {
    ElMessage.error('确认密码与新密码不一致')
    return
  }

  try {
    await handlePassword()

    formVisible.value = false

    Object.keys(form).forEach(key => {
      form[key as keyof typeof form] = ''
    })
  } catch (error) {
    ElMessage.error('修改失败');
    console.dir(error);
  }
}
interface UserInfo {
  code: string
  data: {
    nickname: string
    avatar: string
  }
}

const router = useRouter()
async function back() {
  await request.post('/auth/logout')
  router.push('/login')
}

onMounted(() => {
  getUserInfo()
})
async function getUserInfo() {
  try {
    const response = await request.get('/auth/user/info') as UserInfo
    // console.log(response);
    if (response.code === "0") {
      username.value = response.data.nickname
      avatar.value = response.data.avatar
    } else {
      username.value = '未知用户'
      avatar.value = 'https://sweetchenda.oss-cn-beijing.aliyuncs.com/20250728192224841.png'
      console.log('发生了一些错误！');
    }
  } catch (error) {
    username.value = '加载失败'
    avatar.value = 'https://sweetchenda.oss-cn-beijing.aliyuncs.com/20250728192224841.png'
    console.error('获取用户信息失败:', error);
  }
}

// 修改密码
async function handlePassword() {
  try {
    const data = {
      oldPassword: encryptPassword(form.oldPassword),
      newPassword: encryptPassword(form.newPassword)
    }
    const res = await request.patch('/system/user/password', data)
    console.log(res);

    if (res.code === '0') {
      console.log('修改成功');
      ElMessage.success('修改成功')
      back()
    } else if (res.msg === '当前密码错误') {
      console.log(res.msg);
      ElMessage.error(res.msg)
    } else if (res.msg === '新密码不能与当前密码相同') {
      console.log(res.msg);
      ElMessage.error(res.msg)
    } else {
      console.log('修改失败');
    }
  } catch (error) {
    console.dir(error);
    // console.log('修改密码请求出错:', error);
  }
}
</script>

<style scoped>
ul {
  list-style-type: none;
}

img,
li,
span {
  cursor: pointer;
}

.header {
  display: flex;
  width: 1650px;
  height: 117px;
  background-color: #FFFFFF;
  align-items: center;
  padding-left: 21px;
  margin-bottom: 12px;
}

.header img {
  height: 53px;
  width: 40px;
  margin-right: 30px;
}

.search {
  width: 762px;
  height: 56px;
  display: flex;
  position: relative;
  margin-right: 70px;
}

.search input {
  width: 762px;
  height: 56px;
  border-radius: 8px;
  border: 2px solid #D7D7D7;
  ;
  padding-left: 30px;
}

.search input::placeholder {
  color: #D7D7D7;
  font-size: 18px;
}

.search span {
  position: absolute;
  right: 20px;
  top: 6px;
  font-size: 30px;
  color: #006DB8;
}

.header .picture li {
  position: relative;
}

.header .picture li .circle {
  position: absolute;
  text-align: center;
  border: 3px solid #FFFFFF;
  padding-top: 2px;
  top: -20%;
  right: -20%;
  color: #FFFFFF;
  font-size: 13px;
  width: 26px;
  height: 26px;
  background-color: #006DB8;
  border-radius: 50%;
  z-index: 10;
}

.header .picture li:nth-child(3) .circle {
  background-color: #EC808D;
}

.header .text {
  display: flex;
  margin-top: 6px;
}

.header .text li {
  width: 37px;
  margin-right: 13px;
  font-size: 18px;
  color: #1A70AD;
}

.header .text li:nth-child(2) {
  color: #36A46E;
}

.header .text li:nth-child(3) {
  margin-right: 46px;
}

.header .picture {
  display: flex;
}

.header .picture li {
  width: 52px;
  height: 52px;
  padding-left: 10px;
  border-radius: 8px;
  margin-top: 8px;
  margin-right: 20px;
  background-color: rgba(54, 164, 110, 0.3);
}

.header .picture li:nth-child(3) {
  margin-right: 50px;
}

.header .picture span {
  font-size: 33px;
  color: #36A46E;
}

.header .title {
  display: flex;
  position: relative;
  width: 206px;
  height: 52px;
  background-color: #1A70AD;
  border-radius: 8px;
}

.header .title p {
  margin-left: 13px;
  height: 52px;
  line-height: 52px;
  color: #FFFFFF;
  font-size: 18px;
}

.header .title img {
  border-radius: 50%;
  position: absolute;
  right: -50px;
  width: 56px;
}
</style>